<template>
  <div class="message-type-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>消息类型管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增类型
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" :inline="true" label-width="80px">
          <el-form-item label="类型名称">
            <el-input
                v-model="searchForm.typeName"
                placeholder="请输入类型名称"
                clearable
                style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="类型编码">
            <el-input
                v-model="searchForm.typeCode"
                placeholder="请输入类型编码"
                clearable
                style="width: 150px"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
            >
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          style="width: 100%"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="typeName" label="类型名称" min-width="120" />
        <el-table-column prop="typeCode" label="类型编码" min-width="120" />
        <el-table-column prop="description" label="类型描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
                size="small"
                :type="row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>

        <el-form-item label="类型编码" prop="typeCode">
          <el-input
              v-model="form.typeCode"
              placeholder="请输入类型编码"
              :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="类型描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入类型描述"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { messageTypeApi } from '@/api/message'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  typeName: '',
  typeCode: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: null,
  typeName: '',
  typeCode: '',
  description: '',
  status: 1
})

// 表单验证规则
const rules = {
  typeName: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  typeCode: [
    { required: true, message: '请输入类型编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑消息类型' : '新增消息类型'
})

// 生命周期
onMounted(() => {
  loadTableData()
})

// 方法定义
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await messageTypeApi.getList()

    // 正确处理 ResultVO 格式
    if (response.code === 200) {
      tableData.value = response.data
      pagination.total = response.data.length

      // 如果有搜索条件，进行前端过滤
      if (searchForm.typeName || searchForm.typeCode || searchForm.status) {
        tableData.value = tableData.value.filter(item => {
          const matchesName = !searchForm.typeName ||
              item.typeName.includes(searchForm.typeName)
          const matchesCode = !searchForm.typeCode ||
              item.typeCode.includes(searchForm.typeCode)
          const matchesStatus = !searchForm.status ||
              item.status.toString() === searchForm.status

          return matchesName && matchesCode && matchesStatus
        })
        pagination.total = tableData.value.length
      }
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    typeName: '',
    typeCode: '',
    status: ''
  })
  handleSearch()
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    typeName: '',
    typeCode: '',
    description: '',
    status: 1
  })
  dialogVisible.value = true

  // 清除表单验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, { ...row })
  dialogVisible.value = true

  // 清除表单验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '禁用' : '启用'

  try {
    await ElMessageBox.confirm(`确定要${action}该消息类型吗？`, '提示', {
      type: 'warning'
    })

    let response
    if (row.status === 1) {
      response = await messageTypeApi.disable(row.id)
    } else {
      response = await messageTypeApi.enable(row.id)
    }

    if (response.code === 200) {
      ElMessage.success(`${action}成功`)
      loadTableData()
    } else {
      ElMessage.error(response.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    let response
    if (isEdit.value) {
      response = await messageTypeApi.update(form)
    } else {
      response = await messageTypeApi.add(form)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadTableData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    // 表单验证失败，不进行API调用
    console.error('表单验证失败:', error)
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadTableData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

// 工具方法
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.message-type-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>